import { defineStore } from "pinia";
import { Names } from "./store-name";
import { deleteMenu, queryMenuList, updateMenuInfo } from "@/api/menu";
import { useRequest } from "alova";
import type { TAllMenuInfo, TResponse } from "@/typing/base";
import { arrayToTreeNodes, arrayToTreeTableNodes } from "@/utils/util";
import { updateMenuUsed } from '../api/menu';
import type { TMenuInfoReq, TMenuUsedReq } from "@/typing/menu";
import { cloneDeep } from "lodash";


export const useMenuStore = defineStore(Names.MENU, {
  state() {
    return {
      menuList: <TAllMenuInfo[]>[],
      loading: false
    }
  },
  getters: {
    getNodes(state) {
      const nodes = arrayToTreeTableNodes(state.menuList);
      // const expandedKeys: any = expendAll(nodes)
      console.log(nodes)
      return {
        nodes,
        // expandedKeys
      };
    },
    filterMenu(state) {
      return (id: number) => state.menuList.filter(i => i.id === id)[0]
    },
    getFirstLevelMenu(state) {
      const menus = [{ name: '一级菜单', pid: 0 }]
      state.menuList.forEach(i => {
        menus.push({ name: i.name, pid: i.id })
      })
      return menus
    }
  },
  actions: {
    queryMenuList({ force }: { force?: boolean } = { force: false }) {
      this.loading = true
      const { onSuccess } = useRequest(queryMenuList(), { force: force });
      onSuccess(({ data }) => {
        const { data: { menuList } } = data as TResponse<{ menuList: TAllMenuInfo[] }>
        this.menuList = menuList;
        this.loading = false
      });
    },
    updateMenuUsed(req: TMenuUsedReq, fn: Function) {
      const { onSuccess } = useRequest(updateMenuUsed(req));
      onSuccess(({ data }) => {
        if (data) {
          fn && fn(data);
        }
      });
    },
    updateMenuInfo(req: TMenuInfoReq, fn: Function) {
      const { onSuccess } = useRequest(updateMenuInfo(req));
      onSuccess(({ data }) => {
        if (data) {
          fn && fn(data);
        }
      });
    },
    deleteMenu(id: number, fn: Function) {
      const { onSuccess } = useRequest(deleteMenu(id));
      onSuccess(({ data }) => {
        if (data) {
          fn && fn(data);
        }
      });
    },
  }
})
